package im.vinci.server.common.tmsg;

import com.aliyun.openservices.ons.api.Message;
import im.vinci.server.utils.JsonUtils;

import java.io.Serializable;
import java.util.Hashtable;
import java.util.Properties;

/**
 * Created by tim@vinci on 17/2/10.
 */
public class ProducerMessage implements Serializable{
    private static final TimestampAndHostIdGenerator idGen = new TimestampAndHostIdGenerator();
    private static final byte[] empty_bytes = " ".getBytes();
    private String topic;
    private String key;
    private String tag;
    private String content;
    private Hashtable<Object,Object> userProperties = new Hashtable<>();

    private ProducerMessage(){}

    //key 可以认为是id
    public ProducerMessage(String topic, String tag) {
        this.topic = topic;
        this.key = idGen.getNext();
        this.tag = tag;
    }
    //key 可以认为是id
    public ProducerMessage(String key, String topic, String tag) {
        this.topic = topic;
        this.key = key;
        this.tag = tag;
    }

    public String getTopic() {
        return topic;
    }

    public String getKey() {
        return key;
    }

    public String getTag() {
        return tag;
    }

    public String getContent() {
        return content;
    }

    public ProducerMessage setContent(String content) {
        this.content = content;
        return this;
    }

    public void putUserProperties(final String key, final String value) {
        if (null == this.userProperties) {
            this.userProperties = new Properties();
        }

        if (key != null && value != null) {
            this.userProperties.put(key, value);
        }
    }

    public String getUserProperties(final String key) {
        if (null != this.userProperties) {
            return (String) this.userProperties.get(key);
        }

        return null;
    }

    public Hashtable<Object,Object> getUserProperties() {
        return userProperties;
    }

    public ProducerMessage setUserProperties(Hashtable<Object,Object> userProperties) {
        this.userProperties = userProperties;
        return this;
    }

    Message toMessage() {
        Message message = new Message();
        Properties p = new Properties();
        p.putAll(userProperties);
        message.setUserProperties(p);
        message.setTag(getTag());
        message.setKey(getKey());
        message.setTopic(getTopic());
        if (getContent() == null) {
            message.setBody(new byte[1]);
        } else {
            message.setBody(getContent().getBytes());
        }
        return message;
    }

    public static void main(String[] args) {
        ProducerMessage message = new ProducerMessage("a","b");
        message.putUserProperties("bb","aa");
        System.out.println(JsonUtils.encode(message));
    }
}
